from starlette.endpoints import HTTPEndpoint
from starlette.responses import JSONResponse
import logging
import config
import requests
import random
import json
from redis_connection import redis_conn as redis


class SendRandomMessage(HTTPEndpoint):

    def __init__(self, scope):
        super().__init__(scope)
        self._logger = logging.getLogger(type(self).__name__)

    async def post(self, request):
        data = await request.json()
        target_user = data['target']
        random_number = random.randint(0, 999999)
        try:
            send_text = f"随机测试码为 {random_number:06d}，请注意鉴对。"
            requests.post("https://qyapi.weixin.qq.com/cgi-bin/message/send",
                          params={"access_token": redis.hget(config.ENT_ACCESS_TOKEN, "token").decode()},
                          data=json.dumps({
                              "touser": target_user,
                              "msgtype": "text",
                              "agentid": config.ENT_APP_AGENT,
                              "text": {
                                  "content": send_text
                              },
                              "safe": "0"
                          }, ensure_ascii=False).encode("utf-8"),
                          headers={"Content-Type": "application/json; charset=utf-8"})
            self._logger.debug(f"[FACTORY_MODE] 向 {target_user} 发送了随机测试码 {random_number:06d}")
            result = "1"
        except requests.ConnectionError:
            self._logger.error(f"[FACTORY_MODE] 向 {target_user} 发送随机测试码失败")
            result = "0"
        return JSONResponse({
            "result": result,
            "code": f"{random_number:06d}"
        })
